﻿@model int?
@{
    var guid = Guid.NewGuid().ToString();
}

@Html.Hidden(string.Empty, Model, new { id = guid + "-val" })
<div class="input-group">
    <input type="text" class="form-control" id="@guid-input" autocomplete="off" />
    <span class="input-group-addon" data-toggle="modal" data-target="#@guid" style="cursor:pointer;">选择</span>
</div>
<link href="/CommonRoot/lib/jstree/dist/themes/default/style.min.css" rel="stylesheet" />
<script src="/CommonRoot/lib/jstree/dist/jstree.js"></script>
<div class="modal fade" tabindex="-1" role="dialog" id="@guid">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="panel-default">
                <div class="panel-heading">文章类型</div>
                <div class="panel-body">
                    <div id="@guid-tree"></div>
                </div>
                <div class="panel-footer">
                    <button type="button" id="@guid-btn" class="btn btn-primary">选择</button>
                </div>
            </div>
        </div>
    </div>
</div>
<script>

        $.post({ url: '/cms/articleType/' }).done(function (res) {
            var data = res.result;
            _.each(data, function (item) {
                item.parent = item.parentId;
                item.parentId = null;
                item.text = item.title;
                item.title = null;
                if (!item.parent) item.parent = "#";
            });
            window.articleTypes = data;
            var currentId = "@Model";
            window.tree = $('#@guid-tree').jstree({
                core: {
                    multiple: false,
                    data: window.articleTypes//[{ "id": "ajson1", "parent": "#", "text": "Simple root node" }]
                }
            }).on('loaded.jstree', function (e, data) {
                var inst = data.instance;
                var obj = inst.get_node("@Model");
                inst.select_node(obj);
            });

            if (currentId) {
                var found = _.find(window.articleTypes, function (item) { return item.id == currentId });
                if (found)  $('#@guid-input').val(found.text);
            }
    });

    $('#@guid-input').click(function () { $('#@guid').modal('show') })

    $('#@guid-btn').click(function () {
        var ref = $('#@guid-tree').jstree(true);
        var selectedId = ref.get_selected();
        if (selectedId.length) {
            var id = selectedId[0];
            var found = _.find(window.articleTypes, function (item) { return item.id == id });
            $('#@guid-val').val( selectedId[0]);
            $('#@guid-input').val(found.text);

        }
        $('#@guid').modal('hide');
    });
</script>